﻿using Api.IRepository;
using Api.Model;
using Api.Model.BaseModel;
using Api.Model.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Api.Repository
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly ApiDbContext _db;

        public ApiDbContext GetDbContext()
        {
            return _db;
        }
        public UnitOfWork(ApiDbContext apiDbContext)
        {
            _db = apiDbContext;
        }
        public void SaveChanges()
        {
            if (_db != null)
            {
                BeforeSave();
                _db.SaveChanges();
            }
        }

        public async Task SaveChangesAsync()
        {
            if (_db != null)
            {
                BeforeSave();
                await _db.SaveChangesAsync();
            }
        }

        private void BeforeSave()
        {
            foreach (var entry in _db.ChangeTracker.Entries().ToList())
            {
                switch (entry.State)
                {
                    case EntityState.Added:
                        if (entry.Entity is IAudit)
                        {
                            ((IAudit)entry.Entity).CreationTime = DateTime.Now;
                        }
                        break;
                    case EntityState.Modified:
                        if (entry.Entity is IAudit)
                        {
                            ((IAudit)entry.Entity).LastModificationTime = DateTime.Now;
                        }
                        break;
                    case EntityState.Deleted:
                        if (entry.Entity is IAudit)
                        {
                            var entity = (IAudit)entry.Entity;
                            entity.IsDeleted = true;
                            entity.DeletionTime = DateTime.Now;
                            entry.State = EntityState.Modified;
                        }
                        break;
                }
            }
        }
    }
}
